package com.song.module.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.common.base.UserContextInfo;
import com.song.common.enums.CollectTypeEnums;
import com.song.common.response.PageInfo;
import com.song.framework.context.ContextUserInfoThreadHolder;
import com.song.framework.exception.ServiceException;
import com.song.module.admin.entity.ApComment;
import com.song.module.admin.mapper.ApCommentMapper;
import com.song.module.admin.request.ApCommentRequest;
import com.song.module.admin.service.IApCommentService;
import com.song.module.system.entity.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.song.module.admin.request.ApContentRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.song.module.admin.mapper.ApContentMapper;
import org.springframework.beans.BeanUtils;
import com.song.module.admin.entity.ApContent;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.song.module.admin.service.IApContentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 动态业务层处理
 *
 * @author song
 * @date 2024-03-13
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApContentServiceImpl implements IApContentService {

    private final ApContentMapper baseMapper;

    private final IApCommentService commentService;

    private final ApCommentMapper apCommentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApContent add(ApContentRequest request) {
        ApContent entity = ApContent.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<String> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ApContentRequest request) {
        ApContent entity = ApContent.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public ApContent getById(String id) {
        ApContent apContent = baseMapper.selectById(id);
        String photo = apContent.getPhoto();
        List<String> photos = JSONObject.parseArray(photo, String.class);
        apContent.setPhotoList(photos);
        // 查询评论列表
        ApCommentRequest request = new ApCommentRequest();
        request.setContentId(Long.valueOf(id));
        List<ApComment> list = commentService.list(request);
        apContent.setCommentList(list);
        return apContent;
    }

    @Override
    public PageInfo<ApContent> pageList(ApContentRequest request) {
        Page<ApContent> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<ApContent> query = this.buildWrapper(request);
        IPage<ApContent> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<ApContent> list(ApContentRequest request) {
        LambdaQueryWrapper<ApContent> query = this.buildWrapper(request);
        List<ApContent> contentList = baseMapper.selectList(query);
        if (CollectionUtils.isNotEmpty(contentList)) {
            return contentList.stream().peek(x -> {
                List<ApComment> apContents = apCommentMapper.selectList(Wrappers.lambdaQuery(ApComment.class).eq(ApComment::getContentId, x.getId()));
                int size = apContents.size();
                x.setCollnum(size);
                String photo = x.getPhoto();
                List<String> photos = JSONObject.parseArray(photo, String.class);
                x.setPhotoList(photos);
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void publish(ApContentRequest request) {
        if (CollectionUtils.isEmpty(request.getPhotoList())) {
            throw new ServiceException("请上传你的图片");
        }
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        ApContent apContent = ApContent.builder()
                .avatar(info.getAvatar()).userId(info.getId()).username(info.getUserName())
                .photo(JSONObject.toJSONString(request.getPhotoList()))
                .title(request.getTitle()).subject(request.getSubject()).build();
        baseMapper.insert(apContent);
    }

    @Override
    public void updateCommentNum(Long contentId) {
        ApContent apContent = baseMapper.selectById(contentId);
        if (Objects.nonNull(apContent)) {
            apContent.setCollnum(apContent.getCollnum() + 1);
        }
        baseMapper.updateById(apContent);
    }

    @Override
    public int add_like(Integer type, String id) {
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        ApContent apContent = baseMapper.selectOne(Wrappers.lambdaQuery(ApContent.class).eq(ApContent::getId, id));
        if (Objects.isNull(apContent)) {
            return 0;
        }
        System.out.println(apContent);
        if (CollectTypeEnums.COLLECT.getType().equals(type)) {
            apContent.setLikenum(apContent.getLikenum() + 1);
        } else {
            if (apContent.getLikenum() > 0) {
                apContent.setLikenum(apContent.getLikenum() - 1);
            }
        }



        return  baseMapper.updateById(apContent);
    }

    private LambdaQueryWrapper<ApContent> buildWrapper(ApContentRequest param) {
        LambdaQueryWrapper<ApContent> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSubject())) {
            query.like(ApContent::getSubject, param.getSubject());
        }
        if (StringUtils.isNotBlank(param.getCity())) {
            query.like(ApContent::getCity, param.getCity());
        }
        if (StringUtils.isNotBlank(param.getAvatar())) {
            query.like(ApContent::getAvatar, param.getAvatar());
        }
        query.orderByDesc(BaseEntity::getCreateTime);
        return query;
    }

}
